<?php

namespace moonlight\slide;

use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\web\View;

/**
 * Class GeeWidget 输出滑动验证组件
 * @author zzzyyy
 */
class SlideValidateWidget extends Widget
{
    /**
     * @var string
     */
    public $formId = 'login-form';
    /**
     * @var string
     */
    public $buttonId = 'popup-submit';

    /**
     * @inheritdoc
     */
    public function run()
    {
        parent::run();
        return $this->renderGee();
    }

    /**
     * 输出滑动验证元素
     */
    protected function renderGee()
    {
        $this->registerAssetBundle();
        $this->registerAjaxJs();
        return $this->renderHtml();
    }

    /**
     * @inheritdoc
     */
    protected function renderHtml()
    {
        return Html::tag('div', null, ['id' => 'popup-captcha']);
    }

    /**
     * @inheritdoc
     */
    protected function registerAssetBundle()
    {
        SlideValidateAsset::register($this->getView());
    }

    /**
     * @inheritdoc
     */
    protected function registerAjaxJs()
    {
        $startUrl = Url::to(['gee-start', 't' => time()]);
        $verifyUrl = Url::to(['gee-validate']);
        $action = is_null($this->formId) ? 'console.log(data)' : "$(\"#{$this->formId}\").submit()";
        $jsCode = "
var handlerPopup = function (captchaObj) {
    captchaObj.onSuccess(function () {
        var validate = captchaObj.getValidate();
        $.ajax({
            url: \"{$verifyUrl}\",
            type: \"post\",
            dataType: \"json\",
            data: {
                username: $('#username1').val(),
                password: $('#password1').val(),
                geetest_challenge: validate.geetest_challenge,
                geetest_validate: validate.geetest_validate,
                geetest_seccode: validate.geetest_seccode
            },
            success: function (data) {
                if (data && (data.status === \"success\")) {
                    {$action}
                } else {
                }
            }
        });
    });
    $(\"#{$this->buttonId}\").click(function () {
        captchaObj.show();
    });
    captchaObj.appendTo(\"#popup-captcha\");
};
$.ajax({
    url: \"{$startUrl}\",
    type: \"get\",
    dataType: \"json\",
    success: function (data) {
        initGeetest({
            gt: data.gt,
            challenge: data.challenge,
            product: \"popup\",
            offline: !data.success
        }, handlerPopup);
    }
});";
        $this->getView()->registerJs($jsCode, View::POS_END);
    }
}